import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Col, Form, Input, InputNumber, message, Row, Spin, TreeSelect } from 'antd';
import React, { Ref, useContext, useEffect, useRef } from 'react';
import { IRoleAddEditModal } from '../type';
import pageStyles from '@/common/pageLayout.less';
import { addEditRoleMange, getRoleByID, RouleManageContext } from '../hooks';
import { getCompanyID, getPosIDs, getUserDepID, getUserID, treeSelectIconTransform } from '@/utils';
import { UserOutlined } from '@ant-design/icons';
import { useRequest } from 'umi';

export const RoleAddEditModal: React.FC<IRoleAddEditModal> = ({
  visible, //是否显示
  editAddRows, //选中的值
  onClose, //关闭modal
  tableReload, //刷新列表
}) => {
  const RoleModalRef: Ref<IOneModalRef> = useRef(null); //弹框的ref
  const [roleForm] = Form.useForm();
  const { checkedRowKeys, tableData } = useContext(RouleManageContext); //获取 上下文

  const { detailInfoData, infoLoading } = getRoleByID(editAddRows); //获取详情信息

  useEffect(() => {
    if (detailInfoData && detailInfoData?.id && visible) {
      roleForm?.setFieldsValue(detailInfoData);
    } else {
      roleForm?.setFieldsValue({
        pID: checkedRowKeys?.length > 0 ? checkedRowKeys?.toString() : undefined,
      });
    }
  }, [detailInfoData?.versionNum, visible]);

  /* 关闭弹窗 */
  // const onCloseModal = (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
  const onCloseModal = () => {
    if (RoleModalRef) {
      if (RoleModalRef.current) {
        if (RoleModalRef.current.onModalCancel) {
          RoleModalRef.current.onModalCancel();
        }
      }
    }
  };

  // 新增 或者编辑 方法
  const addEditRoleData = useRequest(
    (payload: any) => {
      if (detailInfoData && detailInfoData?.id) {
        let editRoleParams = {
          ...payload,
          id: detailInfoData?.id,
          versionNum: detailInfoData?.versionNum,
          modifyerID: getUserID(),
          modifyPositionID: getPosIDs(),
          modifyDepartmentID: getUserDepID(),
          modifyCompanyID: getCompanyID(),
        };

        return addEditRoleMange(editRoleParams, 'edit');
      } else {
        let addRoleParams = {
          ...payload,
          // positionID: getPosIDs(),
          userID: getUserID(),
        };

        return addEditRoleMange(addRoleParams, 'add');
      }
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        if (res && res?.msgFlag) {
          message?.success(res?.msg);
          tableReload();
          onCloseModal();
        } else {
          message?.error(res?.msg);
        }
      },
    },
  );

  // modal 点击确认
  const saveAddEditRole = () => {
    roleForm?.validateFields()?.then((values: any) => {
      addEditRoleData?.run({ ...values, isOpen: 1 });
    });
  };

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={RoleModalRef}
        title={editAddRows && editAddRows?.id ? '编辑角色' : '添加角色'}
        width={'40%'}
        onCancel={onClose}
        // className={cls(prefixModal)}
        bodyStyle={{
          padding: '5px 0px',
          // height: window.screen.height * 0.5,
        }}
        centered
        onOk={saveAddEditRole}
        confirmLoading={addEditRoleData?.loading}
      >
        <Spin spinning={editAddRows?.id ? infoLoading || addEditRoleData?.loading : false}>
          <div className={pageStyles['fromView-styles']}>
            <Form layout="inline" form={roleForm}>
              <Row>
                <Col span={24}>
                  <Form.Item
                    name={'name'}
                    label="角色名称"
                    rules={[
                      {
                        required: true,
                        message: '请输入角色名称',
                      },
                    ]}
                    initialValue={detailInfoData && detailInfoData?.id ? detailInfoData.name : undefined}
                  >
                    <Input placeholder={'请输入角色名称'} allowClear />
                  </Form.Item>
                </Col>

                <Col span={24}>
                  <Form.Item name={'pID'} label={'上级角色'} initialValue={detailInfoData && detailInfoData?.id ? detailInfoData.pID : undefined}>
                    <TreeSelect
                      showSearch
                      treeNodeFilterProp={'searchTitle'}
                      placeholder="请选择上级角色"
                      allowClear
                      // onSearch={treeSearchValue}
                      dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                      treeData={treeSelectIconTransform(tableData, <UserOutlined />)}
                      // loading={MapList?.data?.msgFlag ? false : true}
                    />
                  </Form.Item>
                </Col>

                <Col span={24}>
                  <Form.Item
                    label="角色描述"
                    name="describeInfo"
                    rules={[
                      {
                        required: true,
                        message: '请输入角色描述',
                      },
                    ]}
                    initialValue={detailInfoData && detailInfoData?.id ? detailInfoData?.describeInfo : undefined}
                  >
                    <Input.TextArea placeholder="请输入角色描述" allowClear showCount maxLength={200} autoSize={{ minRows: 2, maxRows: 4 }} />
                  </Form.Item>
                </Col>

                <Col span={24}>
                  <Form.Item
                    label="排序"
                    name="seq"
                    rules={[
                      {
                        required: true,
                        message: '请输入排序',
                      },
                    ]}
                    initialValue={detailInfoData && detailInfoData?.id ? detailInfoData?.seq : 0}
                  >
                    <InputNumber placeholder="请输入排序" min={0} />
                  </Form.Item>
                </Col>

                <Col span={24}>
                  <Form.Item label="备注" name="remark" initialValue={detailInfoData && detailInfoData?.id ? detailInfoData?.remark : undefined}>
                    <Input placeholder={'请输入备注'} allowClear />
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </div>
        </Spin>
      </OneModal>
    </>
  );
};
